package web;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import service.impl.UserServiceImpl;
import ssm.pojo.User;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends BeanUser {
    /**
     * @param request  请求
     * @param response 响应
     * @throws IOException
     */

    public void foundUByName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = new String(request.getParameter("username"));
        UserServiceImpl us = new UserServiceImpl();
        User b = us.foundUByName(username);
        if (b!=null) {
            response.getWriter().write("1");
        } else {
            response.getWriter().write("0");
        }
    }

    /**
     * 判断验证码注册
     *
     * @param request  请求
     * @param response 响应
     */
    public void insertUser(HttpServletRequest request, HttpServletResponse response) {
        String yanzheng = request.getParameter("yanzheng");
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        if (yanzheng == null || !yanzheng.equalsIgnoreCase(checkcode_server)) {
            try {
                response.getWriter().write("1");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        ConvertUtils.register(new DateConvert(), Date.class);
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        user.setUid(UUIDUtils.getId());
        //激活码
        user.setCode(UUIDUtils.getCode());
        String password = user.getPassword();
        user.setPassword(MD5Utils.md5(password));

        UserServiceImpl userService = new UserServiceImpl();
        //激活注册用户
        userService.registerUser(user);

        try {
            request.setAttribute("msg", "注册成功,请在邮箱点击邮件激活账户");
            request.getRequestDispatcher("/jsp/jihuo.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 用户点击邮件激活跳转至此方法
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException
     * @throws IOException
     */
    public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.founduByCode(code);
        if (user == null) {
            request.setAttribute("msg", "抱歉激活失败,请重新激活");
            request.getRequestDispatcher("/jsp/jihuo.jsp").forward(request, response);
        } else {
            request.setAttribute("msg", "激活成功,请<a href='http://localhost:8080/11_22_war/jsp/login.jsp'>登录</a>");
            request.getRequestDispatcher("/jsp/jihuo.jsp").forward(request, response);
        }
    }

    /**
     * 登录
     *
     * @param request  请求
     * @param response 响应
     */

    public void myLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String yanzheng = request.getParameter("yanzheng");
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        if (yanzheng == null || !yanzheng.equalsIgnoreCase(checkcode_server)) {
            response.getWriter().write("1");
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(username, password);
        if (user == null) {
            request.setAttribute("msg", "抱歉用户名或密码错误");
            request.getRequestDispatcher("/jsp/jihuo.jsp").forward(request, response);
        } else {
            if (user.getState() != 1) {
                request.setAttribute("msg", "当前用户未激活,请查看邮件激活账户");
                String text = "欢迎注册,请您<a href='http://localhost:8080/11_22_war/user?methodName=active&code=" + user.getCode() + "'>点击激活</a>";
                MailUtils.sendMail(user.getEmail(), text, "用户激活邮件");
                request.getRequestDispatcher("/jsp/jihuo.jsp").forward(request, response);
            }
        }
        session.setAttribute("user",user);

        String auto_user = request.getParameter("auto_user");
        if(!"AutoUser".equals(auto_user)){
            Cookie autouser = new Cookie("autouser", "");
            autouser.setMaxAge(0);
            response.addCookie(autouser);
        }else {
            String c = user.getUsername()+":"+user.getPassword();
            String encode = URLEncoder.encode(c, "utf-8");
            Cookie autouser = new Cookie("autouser", encode);
            autouser.setMaxAge(60*60*24*30);
            response.addCookie(autouser);
        }
        response.sendRedirect(request.getContextPath()+"/");
    }

    /**
     * 账户退出
     * @param request 请求
     * @param response 响应
     */
    public void secedeUser(HttpServletRequest request, HttpServletResponse response){

        try {
            request.getSession().removeAttribute("user");
            response.sendRedirect(request.getContextPath() +"/index.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
